package com.twu.biblioteca;

import java.util.Scanner;

public class OptionLogIn implements Option {

    private Scanner scanner;
    private UserLog userLog;

    public OptionLogIn(UserLog userLog, Scanner scanner) {
        this.userLog = userLog;
        this.scanner = scanner;
    }

    public User run(User user) {

        requestUsernameInput();
        Integer usernameInput = getUsernameInput();

        requestPasswordInput();
        String passwordInput = getPasswordInput();

        User newUser = attemptLogin(usernameInput, passwordInput);

        if (newUser == null) {
            printLogInFailure();
            return null;
        }

        printLogInSuccess();
        return newUser;
    }

    private User attemptLogin(Integer usernameInput, String passwordInput) {

        User userToLogIn = attemptToGetUser(usernameInput);
        userToLogIn = logInIfCorrectPassword(userToLogIn, passwordInput);
        return userToLogIn;
    }

    private User attemptToGetUser(Integer usernameInput) {

        if (userLog.isValid(usernameInput)) {
            return userLog.getUser(usernameInput);
        }

        return null;
    }

    private User logInIfCorrectPassword(User user, String passwordInput) {

        if ((user != null) && user.passwordEquals(passwordInput)) {
            user.setLoggedIn();
            return user;
        }

        return null;
    }

    private void requestUsernameInput() {
        System.out.print("Username: ");
    }

    private void requestPasswordInput() {
        System.out.print("Password: ");
    }

    private Integer getUsernameInput() {
        return parseUsernameInput(scanner.nextLine());
    }

    private Integer parseUsernameInput(String usernameInput) {

        Integer usernameInputInteger;
        String[] usernameInputSplit = usernameInput.split("-");

        if (usernameInputSplit.length != 2) {
            return new Integer(0);
        }

        try {
            int usernameIntPart1 = Integer.parseInt(usernameInputSplit[0]);
            int usernameIntPart2 = Integer.parseInt(usernameInputSplit[1]);
            usernameInputInteger = new Integer((10000 * usernameIntPart1) + usernameIntPart2);
        }
        catch (NumberFormatException e) {
            return new Integer(0);
        }

        return usernameInputInteger;
    }

    private String getPasswordInput() {
        return scanner.nextLine();
    }

    public String menuDescription() {
        return "Log in";
    }

    private void printLogInFailure() {
        System.out.println("Log in failed.");
    }

    private void printLogInSuccess() {
        System.out.println("Log in succeeded.");
    }
}